home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / pcl / src-16f.lha / compiler / ltn.lisp < prev    next >
Encoding:
Text File  |  1992-02-15  |  39.5 KB  |  1,092 lines

  1. ;;; -*- Package: C; Log: C.Log -*-
  2. ;;;
  3. ;;; **********************************************************************
  4. ;;; This code was written as part of the CMU Common Lisp project at
  5. ;;; Carnegie Mellon University, and has been placed in the public domain.
  6. ;;; If you want to use this code or any part of CMU Common Lisp, please contact
  7. ;;; Scott Fahlman or slisp-group@cs.cmu.edu.
  8. ;;;
  9. (ext:file-comment
  10.   "$Header: ltn.lisp,v 1.30 92/02/13 09:30:27 ram Exp $")
  11. ;;;
  12. ;;; **********************************************************************
  13. ;;;
  14. ;;;    This file contains the LTN pass in the compiler.  LTN allocates
  15. ;;; expression evaluation TNs, makes nearly all the implementation policy
  16. ;;; decisions, and also does a few other random things.
  17. ;;;
  18. ;;; Written by Rob MacLachlan
  19. ;;;
  20. (in-package "C")
  21. (in-package "EXTENSIONS")
  22. (export '(*efficiency-note-limit* *efficiency-note-cost-threshold*))
  23. (in-package "C")
  24.  
  25.  
  26. ;;;; Utilities:
  27.  
  28. ;;; Translation-Policy  --  Internal
  29. ;;;
  30. ;;;    Return the policies keyword indicated by the node policy.
  31. ;;;
  32. (defun translation-policy (node)
  33.   (declare (type node node))
  34.   (let* ((cookie (lexenv-cookie (node-lexenv node)))
  35.      (safety (cookie-safety cookie))
  36.      (space (max (cookie-space cookie)
  37.              (cookie-cspeed cookie)))
  38.      (speed (cookie-speed cookie)))
  39.     (if (zerop safety)
  40.     (if (>= speed space) :fast :small)
  41.     (if (>= speed space) :fast-safe :safe))))
  42.  
  43.  
  44. ;;; Policy-Safe-P  --  Interface
  45. ;;;
  46. ;;;    Return true if Policy is a safe policy.
  47. ;;;
  48. (proclaim '(inline policy-safe-p))
  49. (defun policy-safe-p (policy)
  50.   (declare (type policies policy))
  51.   (or (eq policy :safe) (eq policy :fast-safe)))
  52.  
  53.  
  54. ;;; FLUSH-TYPE-CHECK  --  Internal
  55. ;;;
  56. ;;;    Called when an unsafe policy indicates that no type check should be done
  57. ;;; on CONT.  We delete the type check unless it is :ERROR (indicating a
  58. ;;; compile-time type error.)
  59. ;;;
  60. (proclaim '(inline flush-type-check))
  61. (defun flush-type-check (cont)
  62.   (declare (type continuation cont))
  63.   (when (member (continuation-type-check cont) '(t :no-check))
  64.     (setf (continuation-%type-check cont) :deleted))
  65.   (undefined-value))
  66.  
  67.  
  68. ;;; Continuation-PType  --  Internal
  69. ;;;
  70. ;;;    A annotated continuation's primitive-type.
  71. ;;;
  72. (proclaim '(inline continuation-ptype))
  73. (defun continuation-ptype (cont)
  74.   (declare (type continuation cont))
  75.   (ir2-continuation-primitive-type (continuation-info cont)))
  76.  
  77.  
  78. ;;; LEGAL-IMMEDIATE-CONSTANT-P  --  Interface
  79. ;;;
  80. ;;;    Return true if a constant Leaf is of a type which we can legally
  81. ;;; directly reference in code.  Named constants with arbitrary pointer values
  82. ;;; cannot, since we must preserve EQLness.
  83. ;;;
  84. (defun legal-immediate-constant-p (leaf)
  85.   (declare (type constant leaf))
  86.   (or (null (leaf-name leaf))
  87.       (typecase (constant-value leaf)
  88.     ((or number character) t)
  89.     (symbol (symbol-package (constant-value leaf)))
  90.     (t nil))))
  91.  
  92.  
  93. ;;; Continuation-Delayed-Leaf  --  Internal
  94. ;;;
  95. ;;;    If Cont is used only by a Ref to a leaf that can be delayed, then return
  96. ;;; the leaf, otherwise return NIL.
  97. ;;;
  98. (defun continuation-delayed-leaf (cont)
  99.   (declare (type continuation cont)) 
  100.   (let ((use (continuation-use cont)))
  101.     (and (ref-p use)
  102.      (let ((leaf (ref-leaf use)))
  103.        (etypecase leaf
  104.          (lambda-var (if (null (lambda-var-sets leaf)) leaf nil))
  105.          (constant (if (legal-immediate-constant-p leaf) leaf nil))
  106.          ((or functional global-var) nil))))))
  107.  
  108.  
  109. ;;; Annotate-1-Value-Continuation  --  Internal
  110. ;;;
  111. ;;;    Annotate a normal single-value continuation.  If its only use is a ref
  112. ;;; that we are allowed to delay the evaluation of, then we mark the
  113. ;;; continuation for delayed evaluation, otherwise we assign a TN to hold the
  114. ;;; continuation's value.  If the continuation has a type check, we make the TN
  115. ;;; according to the proven type to ensure that the possibly erroneous value
  116. ;;; can be represented.
  117. ;;;
  118. (defun annotate-1-value-continuation (cont)
  119.   (declare (type continuation cont))
  120.   (let ((info (continuation-info cont)))
  121.     (assert (eq (ir2-continuation-kind info) :fixed))
  122.     (cond
  123.      ((continuation-delayed-leaf cont)
  124.       (setf (ir2-continuation-kind info) :delayed))
  125.      ((member (continuation-type-check cont) '(:deleted nil))
  126.       (setf (ir2-continuation-locs info)
  127.         (list (make-normal-tn (ir2-continuation-primitive-type info)))))
  128.      (t
  129.       (setf (ir2-continuation-locs info)
  130.         (list (make-normal-tn
  131.            (primitive-type
  132.             (single-value-type (continuation-proven-type cont)))))))))
  133.   (undefined-value))
  134.  
  135.  
  136. ;;; Annotate-Ordinary-Continuation  --  Internal
  137. ;;;
  138. ;;;    Make an IR2-Continuation corresponding to the continuation type and then
  139. ;;; do Annotate-1-Value-Continuation.  If Policy isn't a safe policy, then we
  140. ;;; clear the type-check flag.
  141. ;;;
  142. (defun annotate-ordinary-continuation (cont policy)
  143.   (declare (type continuation cont)
  144.        (type policies policy))
  145.   (let ((info (make-ir2-continuation
  146.            (primitive-type (continuation-type cont)))))
  147.     (setf (continuation-info cont) info)
  148.     (unless (policy-safe-p policy) (flush-type-check cont))
  149.     (annotate-1-value-continuation cont))
  150.   (undefined-value))
  151.  
  152.  
  153. ;;; Annotate-Function-Continuation  --  Internal
  154. ;;;
  155. ;;;    Annotate the function continuation for a full call.  If the only
  156. ;;; reference is to a global symbol function and Delay is true, then we delay
  157. ;;; the reference, otherwise we annotate for a single value.
  158. ;;;
  159. ;;;   Unlike for an argument, we only clear the type check flag when the policy
  160. ;;; is unsafe, since the check for a valid function object must be done before
  161. ;;; the call.
  162. ;;;
  163. (defun annotate-function-continuation (cont policy &optional (delay t))
  164.   (declare (type continuation cont) (type policies policy))
  165.   (unless (policy-safe-p policy) (flush-type-check cont))
  166.   (let* ((ptype (primitive-type
  167.          (if (member (continuation-type-check cont) '(:deleted nil))
  168.              (continuation-type cont)
  169.              (single-value-type (continuation-proven-type cont)))))
  170.      (info (make-ir2-continuation ptype)))
  171.     (setf (continuation-info cont) info)
  172.     (let ((name (continuation-function-name cont t)))
  173.       (if (and delay name (symbolp name))
  174.       (setf (ir2-continuation-kind info) :delayed)
  175.       (setf (ir2-continuation-locs info) (list (make-normal-tn ptype))))))
  176.   (undefined-value))
  177.  
  178.  
  179. ;;; FLUSH-FULL-CALL-TAIL-TRANSFER  --  Internal
  180. ;;;
  181. ;;;    If TAIL-P is true, then we check to see if the call can really be a tail
  182. ;;; call by seeing if this function's return convention is :UNKNOWN.  If so, we
  183. ;;; move the call block succssor link from the return block to the component
  184. ;;; tail (after ensuring that they are in separate blocks.)  This allows the
  185. ;;; return to be deleted when there are no non-tail uses.
  186. ;;;
  187. (defun flush-full-call-tail-transfer (call)
  188.   (declare (type basic-combination call))
  189.   (let ((tails (and (node-tail-p call)
  190.             (lambda-tail-set (node-home-lambda call)))))
  191.     (when tails
  192.       (cond ((eq (return-info-kind (tail-set-info tails)) :unknown)
  193.          (node-ends-block call)
  194.          (let ((block (node-block call)))
  195.            (unlink-blocks block (first (block-succ block)))
  196.            (link-blocks block (component-tail (block-component block)))))
  197.         (t
  198.          (setf (node-tail-p call) nil)))))
  199.   (undefined-value))
  200.  
  201.  
  202. ;;; LTN-Default-Call  --  Internal
  203. ;;;
  204. ;;;    Set up stuff to do a full call for Call.  We always flush arg type
  205. ;;; checks, but do it after annotation when the policy is safe, since we don't
  206. ;;; want to choose the TNs according to a type assertions that may not hold.
  207. ;;;
  208. ;;;    We set the kind to :FULL or :FUNNY, depending on whether there is an
  209. ;;; IR2-CONVERT method.  If a funny function, then we inhibit tail recursion,
  210. ;;; since the IR2 convert method is going to want to deliver values normally.
  211. ;;;
  212. (defun ltn-default-call (call policy)
  213.   (declare (type combination call) (type policies policy))
  214.   (annotate-function-continuation (basic-combination-fun call) policy)
  215.  
  216.   (let ((safe-p (policy-safe-p policy)))
  217.     (dolist (arg (basic-combination-args call))
  218.       (unless safe-p (flush-type-check arg))
  219.       (unless (continuation-info arg)
  220.     (setf (continuation-info arg)
  221.           (make-ir2-continuation
  222.            (primitive-type
  223.         (continuation-type arg)))))
  224.       (annotate-1-value-continuation arg)
  225.       (when safe-p (flush-type-check arg))))
  226.  
  227.   (let ((kind (basic-combination-kind call)))
  228.     (cond ((and (function-info-p kind)
  229.         (function-info-ir2-convert kind))
  230.        (setf (basic-combination-info call) :funny)
  231.        (setf (node-tail-p call) nil))
  232.       (t
  233.        (setf (basic-combination-info call) :full)
  234.        (flush-full-call-tail-transfer call))))
  235.   
  236.   (undefined-value))
  237.  
  238.  
  239. ;;; Annotate-Unknown-Values-Continuation  --  Internal
  240. ;;;
  241. ;;; Annotate a continuation for unknown multiple values:
  242. ;;; -- Delete any type check, regardless of policy, since we IR2 conversion
  243. ;;;    isn't prepared to check unknown-values continuations.  If we delete a
  244. ;;;    type check when the policy is safe, then we emit a warning.
  245. ;;; -- Add the continuation to the IR2-Block-Popped if it is used across a
  246. ;;;    block boundry.
  247. ;;; -- Assign a :Unknown IR2-Continuation.
  248. ;;;
  249. ;;; Note: it is critical that this be called only during LTN analysis of Cont's
  250. ;;; DEST, and called in the order that the continuations are received.
  251. ;;; Otherwise the IR2-Block-Popped and IR2-Component-Values-XXX will get all
  252. ;;; messed up.
  253. ;;;
  254. (defun annotate-unknown-values-continuation (cont policy)
  255.   (declare (type continuation cont) (type policies policy))
  256.   (when (eq (continuation-type-check cont) t)
  257.     (let* ((dest (continuation-dest cont))
  258.        (*compiler-error-context* dest))
  259.       (when (and (policy-safe-p policy)
  260.          (policy dest (>= safety brevity)))
  261.     (compiler-note "Unable to check type assertion in unknown-values ~
  262.                     context:~% ~S"
  263.                (continuation-asserted-type cont))))
  264.     (setf (continuation-%type-check cont) :deleted))
  265.  
  266.   (let* ((block (node-block (continuation-dest cont)))
  267.      (use (continuation-use cont))
  268.      (2block (block-info block)))
  269.     (unless (and use (eq (node-block use) block))
  270.       (setf (ir2-block-popped 2block)
  271.         (nconc (ir2-block-popped 2block) (list cont)))))
  272.  
  273.   (let ((2cont (make-ir2-continuation nil)))
  274.     (setf (ir2-continuation-kind 2cont) :unknown)
  275.     (setf (ir2-continuation-locs 2cont) (make-unknown-values-locations))
  276.     (setf (continuation-info cont) 2cont))
  277.  
  278.   (undefined-value))
  279.  
  280.  
  281. ;;; Annotate-Fixed-Values-Continuation  --  Internal
  282. ;;;
  283. ;;;    Annotate Cont for a fixed, but arbitrary number of values, of the
  284. ;;; specified primitive Types.  If the continuation has a type check, we
  285. ;;; annotate for the number of values indicated by Types, but only use proven
  286. ;;; type information.
  287. ;;;
  288. (defun annotate-fixed-values-continuation (cont policy types)
  289.   (declare (type continuation cont) (type policies policy) (list types))
  290.   (unless (policy-safe-p policy) (flush-type-check cont))
  291.  
  292.   (let ((res (make-ir2-continuation nil)))
  293.     (if (member (continuation-type-check cont) '(:deleted nil))
  294.     (setf (ir2-continuation-locs res) (mapcar #'make-normal-tn types))
  295.     (let* ((proven (mapcar #'(lambda (x)
  296.                    (make-normal-tn (primitive-type x)))
  297.                    (values-types
  298.                 (continuation-proven-type cont))))
  299.            (num-proven (length proven))
  300.            (num-types (length types)))
  301.       (setf (ir2-continuation-locs res)
  302.         (cond
  303.          ((< num-proven num-types)
  304.           (append proven
  305.               (make-n-tns (- num-types num-proven)
  306.                       (backend-any-primitive-type *backend*))))
  307.          ((> num-proven num-types)
  308.           (subseq proven 0 num-types))
  309.          (t
  310.           proven)))))
  311.     (setf (continuation-info cont) res))
  312.  
  313.   (undefined-value))
  314.  
  315.  
  316. ;;;; Node-specific analysis functions:
  317.  
  318. ;;; LTN-Analyze-Return  --  Internal
  319. ;;;
  320. ;;;    Annotate the result continuation for a function.  We use the Return-Info
  321. ;;; computed by GTN to determine how to represent the return values within the
  322. ;;; function:
  323. ;;; -- If the tail-set has a fixed values count, then use that many values.
  324. ;;; -- If the actual uses of the result continuation in this function have a
  325. ;;;    fixed number of values (after intersection with the assertion), then use
  326. ;;;    that number.  We throw out TAIL-P :FULL and :LOCAL calls, since we know
  327. ;;;    they will truly end up as TR calls.  We can use the
  328. ;;;    BASIC-COMBINATION-INFO even though it is assigned by this phase, since
  329. ;;;    the initial value NIL doesn't look like a TR call.
  330. ;;;
  331. ;;;    If there are *no* non-tail-call uses, then it falls out that we annotate
  332. ;;;    for one value (type is NIL), but the return will end up being deleted.
  333. ;;;
  334. ;;;    In non-perverse code, the DFO walk will reach all uses of the result
  335. ;;;    continuation before it reaches the RETURN.  In perverse code, we may
  336. ;;;    annotate for unknown values when we didn't have to. 
  337. ;;; -- Otherwise, we must annotate the continuation for unknown values.
  338. ;;;
  339. (defun ltn-analyze-return (node policy)
  340.   (declare (type creturn node) (type policies policy))
  341.   (let* ((cont (return-result node))
  342.      (fun (return-lambda node))
  343.      (returns (tail-set-info (lambda-tail-set fun)))
  344.      (types (return-info-types returns)))
  345.     (if (eq (return-info-count returns) :unknown)
  346.     (collect ((res *empty-type* values-type-union))
  347.       (do-uses (use (return-result node))
  348.         (unless (and (node-tail-p use)
  349.              (basic-combination-p use)
  350.              (member (basic-combination-info use) '(:local :full)))
  351.           (res (node-derived-type use))))
  352.       
  353.       (let ((int (values-type-intersection
  354.               (res)
  355.               (continuation-asserted-type cont))))
  356.         (multiple-value-bind
  357.         (types kind)
  358.         (values-types (if (eq int *empty-type*) (res) int))
  359.           (if (eq kind :unknown)
  360.           (annotate-unknown-values-continuation cont policy)
  361.           (annotate-fixed-values-continuation
  362.            cont policy
  363.            (mapcar #'primitive-type types))))))
  364.     (annotate-fixed-values-continuation cont policy types)))
  365.  
  366.   (undefined-value))
  367.  
  368.  
  369. ;;; LTN-Analyze-MV-Bind  --  Internal
  370. ;;;
  371. ;;;    Annotate the single argument continuation as a fixed-values
  372. ;;; continuation.  We look at the called lambda to determine number and type of
  373. ;;; return values desired.  It is assumed that only a function that
  374. ;;; Looks-Like-An-MV-Bind will be converted to a local call.
  375. ;;;
  376. (defun ltn-analyze-mv-bind (call policy)
  377.   (declare (type mv-combination call)
  378.        (type policies policy))
  379.   (setf (basic-combination-kind call) :local)
  380.   (setf (node-tail-p call) nil)
  381.   (annotate-fixed-values-continuation
  382.    (first (basic-combination-args call)) policy
  383.    (mapcar #'(lambda (var)
  384.            (primitive-type (basic-var-type var)))
  385.        (lambda-vars
  386.         (ref-leaf
  387.          (continuation-use
  388.           (basic-combination-fun call))))))
  389.   (undefined-value))
  390.  
  391.  
  392. ;;; LTN-Analyze-MV-Call  --  Internal
  393. ;;;
  394. ;;;    We force all the argument continuations to use the unknown values
  395. ;;; convention.  The continuations are annotated in reverse order, since the
  396. ;;; last argument is on top, thus must be popped first.  We disallow delayed
  397. ;;; evaluation of the function continuation to simplify IR2 conversion of MV
  398. ;;; call.
  399. ;;;
  400. ;;;    We could be cleverer when we know the number of values returned by the
  401. ;;; continuations, but optimizations of MV-Call are probably unworthwhile.
  402. ;;;
  403. ;;;    We are also responsible for handling THROW, which is represented in IR1
  404. ;;; as an mv-call to the %THROW funny function.  We annotate the tag
  405. ;;; continuation for a single value and the values continuation for unknown
  406. ;;; values.
  407. ;;;
  408. (defun ltn-analyze-mv-call (call policy)
  409.   (declare (type mv-combination call))
  410.   (let ((fun (basic-combination-fun call))
  411.     (args (basic-combination-args call)))
  412.     (cond ((eq (continuation-function-name fun) '%throw)
  413.        (setf (basic-combination-info call) :funny)
  414.        (annotate-ordinary-continuation (first args) policy)
  415.        (annotate-unknown-values-continuation (second args) policy)
  416.        (setf (node-tail-p call) nil))
  417.       (t
  418.        (setf (basic-combination-info call) :full)
  419.        (annotate-function-continuation (basic-combination-fun call)
  420.                        policy nil)
  421.        (dolist (arg (reverse args))
  422.          (annotate-unknown-values-continuation arg policy))
  423.        (flush-full-call-tail-transfer call))))
  424.  
  425.   (undefined-value))
  426.  
  427.  
  428. ;;; LTN-Analyze-Local-Call  --  Internal
  429. ;;;
  430. ;;;    Annotate the arguments as ordinary single-value continuations.  If the
  431. ;;; call is a tail call, make sure that is linked directly to the bind node.
  432. ;;; Usually it will be, but calls from XEPs and calls that might have needed a
  433. ;;; cleanup after them won't have been swung over yet, since we weren't sure
  434. ;;; they would really be TR until now.
  435. ;;;
  436. (defun ltn-analyze-local-call (call policy)
  437.   (declare (type combination call)
  438.        (type policies policy))
  439.   (setf (basic-combination-info call) :local)
  440.  
  441.   (dolist (arg (basic-combination-args call))
  442.     (when arg
  443.       (annotate-ordinary-continuation arg policy)))
  444.  
  445.   (when (node-tail-p call)
  446.     (let ((caller (node-home-lambda call))
  447.       (callee (combination-lambda call)))
  448.       (assert (eq (lambda-tail-set caller)
  449.           (lambda-tail-set (lambda-home callee))))
  450.       (node-ends-block call)
  451.       (let ((block (node-block call)))
  452.     (unlink-blocks block (first (block-succ block)))
  453.     (link-blocks block (node-block (lambda-bind callee))))))
  454.   (undefined-value))
  455.  
  456.  
  457. ;;; LTN-Analyze-Set  --  Internal
  458. ;;;
  459. ;;;    Annotate the value continuation.
  460. ;;;
  461. (defun ltn-analyze-set (node policy)
  462.   (declare (type cset node) (type policies policy))
  463.   (setf (node-tail-p node) nil)
  464.   (annotate-ordinary-continuation (set-value node) policy)
  465.   (undefined-value))
  466.  
  467.  
  468. ;;; LTN-Analyze-If  --  Internal  
  469. ;;;
  470. ;;;    If the only use of the Test continuation is a combination annotated with
  471. ;;; a conditional template, then don't annotate the continuation so that IR2
  472. ;;; conversion knows not to emit any code, otherwise annotate as an ordinary
  473. ;;; continuation.  Since we only use a conditional template if the call
  474. ;;; immediately precedes the IF node in the same block, we know that any
  475. ;;; predicate will already be annotated.
  476. ;;;
  477. (defun ltn-analyze-if (node policy)
  478.   (declare (type cif node) (type policies policy))
  479.   (setf (node-tail-p node) nil)
  480.   (let* ((test (if-test node))
  481.      (use (continuation-use test)))
  482.     (unless (and (combination-p use)
  483.          (let ((info (basic-combination-info use)))
  484.            (and (template-p info)
  485.             (eq (template-result-types info) :conditional))))
  486.       (annotate-ordinary-continuation test policy)))
  487.   (undefined-value))
  488.  
  489.  
  490. ;;; LTN-Analyze-Exit  --  Internal
  491. ;;;
  492. ;;;    If there is a value continuation, then annotate it for unknown values.
  493. ;;; In this case, the exit is non-local, since all other exits are deleted or
  494. ;;; degenerate by this point.
  495. ;;;
  496. (defun ltn-analyze-exit (node policy)
  497.   (setf (node-tail-p node) nil)
  498.   (let ((value (exit-value node)))
  499.     (when value
  500.       (annotate-unknown-values-continuation value policy)))
  501.   (undefined-value))
  502.  
  503.  
  504. ;;; LTN annotate %Unwind-Protect  --  Internal
  505. ;;;
  506. ;;;    We need a special method for %Unwind-Protect that ignores the cleanup
  507. ;;; function.  We don't annotate either arg, since we don't need them at
  508. ;;; run-time.
  509. ;;;
  510. ;;; [The default is o.k. for %Catch, since environment analysis converted the
  511. ;;; reference to the escape function into a constant reference to the
  512. ;;; NLX-Info.]
  513. ;;;
  514. (defoptimizer (%unwind-protect ltn-annotate) ((escape cleanup) node policy)
  515.   policy ; Ignore...
  516.   (setf (basic-combination-info node) :funny)
  517.   (setf (node-tail-p node) nil)
  518.   )
  519.  
  520.  
  521. ;;; LTN annotate %Slot-Setter, %Slot-Accessor  --  Internal
  522. ;;;
  523. ;;;    Both of these functions need special LTN-annotate methods, since we only
  524. ;;; want to clear the Type-Check in unsafe policies.  If we allowed the call to
  525. ;;; be annotated as a full call, then no type checking would be done.
  526. ;;;
  527. ;;;    We also need a special LTN annotate method for %Slot-Setter so that the
  528. ;;; function is ignored.  This is because the reference to a SETF function
  529. ;;; can't be delayed, so IR2 conversion would have already emitted a call to
  530. ;;; FDEFINITION by the time the IR2 convert method got control.
  531. ;;;
  532. (defoptimizer (%slot-accessor ltn-annotate) ((struct) node policy)
  533.   (setf (basic-combination-info node) :funny)
  534.   (setf (node-tail-p node) nil)
  535.   (annotate-ordinary-continuation struct policy))
  536. ;;;
  537. (defoptimizer (%slot-setter ltn-annotate) ((struct value) node policy)
  538.   (setf (basic-combination-info node) :funny)
  539.   (setf (node-tail-p node) nil)
  540.   (annotate-ordinary-continuation struct policy)
  541.   (annotate-ordinary-continuation value policy))
  542.  
  543.  
  544. ;;;; Known call annotation:
  545.  
  546. ;;; OPERAND-RESTRICTION-OK  --  Interface
  547. ;;;
  548. ;;;    Return true if Restr is satisfied by Type.  If T-OK is true, then a T
  549. ;;; restriction allows any operand type.  This is also called by IR2tran when
  550. ;;; it determines whether a result temporary needs to be made, and by
  551. ;;; representation selection when it is deciding which move VOP to use.
  552. ;;; Cont and TN are used to test for constant arguments.
  553. ;;;
  554. (proclaim '(inline operand-restriction-ok))
  555. (defun operand-restriction-ok (restr type &key cont tn (t-ok t))
  556.   (declare (type (or (member *) cons) restr)
  557.        (type primitive-type type)
  558.        (type (or continuation null) cont)
  559.        (type (or tn null) tn))
  560.   (if (eq restr '*)
  561.       t
  562.       (ecase (first restr)
  563.     (:or
  564.      (dolist (mem (rest restr) nil)
  565.        (when (or (and t-ok (eq mem (backend-any-primitive-type *backend*)))
  566.              (eq mem type))
  567.          (return t))))
  568.     (:constant
  569.      (cond (cont
  570.         (and (constant-continuation-p cont)
  571.              (funcall (second restr) (continuation-value cont))))
  572.            (tn
  573.         (and (eq (tn-kind tn) :constant)
  574.              (funcall (second restr) (tn-value tn))))
  575.            (t
  576.         (error "Neither CONT nor TN supplied.")))))))
  577.  
  578.   
  579. ;;; Template-Args-OK  --  Internal
  580. ;;;
  581. ;;;    Check that the argument type restriction for Template are satisfied in
  582. ;;; call.  If an argument's TYPE-CHECK is :NO-CHECK and our policy is safe,
  583. ;;; then only :SAFE templates are o.k.
  584. ;;;
  585. (defun template-args-ok (template call safe-p)
  586.   (declare (type template template)
  587.        (type combination call))
  588.   (let ((mtype (template-more-args-type template)))
  589.     (do ((args (basic-combination-args call) (cdr args))
  590.      (types (template-arg-types template) (cdr types)))
  591.     ((null types)
  592.      (cond ((null args) t)
  593.            ((not mtype) nil)
  594.            (t
  595.         (dolist (arg args t)
  596.           (unless (operand-restriction-ok mtype
  597.                           (continuation-ptype arg))
  598.             (return nil))))))
  599.       (when (null args) (return nil))
  600.       (let ((arg (car args))
  601.         (type (car types)))
  602.     (when (and (eq (continuation-type-check arg) :no-check)
  603.            safe-p
  604.            (not (eq (template-policy template) :safe)))
  605.       (return nil))
  606.     (unless (operand-restriction-ok type (continuation-ptype arg)
  607.                     :cont arg)
  608.       (return nil))))))
  609.  
  610.  
  611. ;;; Template-Results-OK  --  Internal
  612. ;;;
  613. ;;;    Check that Template can be used with the specifed Result-Type.  Result
  614. ;;; type checking is pretty different from argument type checking due to the
  615. ;;; relaxed rules for values count.  We succeed if for each required result,
  616. ;;; there is a positional restriction on the value that is at least as good.
  617. ;;; If we run out of result types before we run out of restrictions, then we
  618. ;;; only suceed if the leftover restrictions are *.  If we run out of
  619. ;;; restrictions before we run out of result types, then we always win.
  620. ;;;
  621. (defun template-results-ok (template result-type)
  622.   (declare (type template template)
  623.        (type ctype result-type))
  624.   (when (template-more-results-type template)
  625.     (error "~S has :MORE results with :TRANSLATE." (template-name template)))
  626.   (let ((types (template-result-types template)))
  627.     (cond
  628.      ((values-type-p result-type)
  629.       (do ((ltypes (append (args-type-required result-type)
  630.                (args-type-optional result-type))
  631.            (rest ltypes))
  632.        (types types (rest types)))
  633.       ((null ltypes)
  634.        (dolist (type types t)
  635.          (unless (eq type '*)
  636.            (return nil))))
  637.     (when (null types) (return t))
  638.     (let ((type (first types)))
  639.       (unless (operand-restriction-ok type
  640.                       (primitive-type (first ltypes)))
  641.         (return nil)))))
  642.      (types
  643.       (operand-restriction-ok (first types) (primitive-type result-type)))
  644.      (t t))))
  645.  
  646.  
  647. ;;; IS-OK-TEMPLATE-USE  --  Internal
  648. ;;;
  649. ;;; Return true if Call is an ok use of Template according to Safe-P.  
  650. ;;; -- If the template has a Guard that isn't true, then we ignore the
  651. ;;;    template, not even considering it to be rejected.
  652. ;;; -- If the argument type restrictions aren't satisfied, then we reject the
  653. ;;;    template.
  654. ;;; -- If the template is :Conditional, then we accept it only when the
  655. ;;;    destination of the value is an immediately following IF node.
  656. ;;; -- If either the template is safe or the policy is unsafe (i.e. we can
  657. ;;;    believe output assertions), then we test against the intersection of the
  658. ;;;    node derived type and the continuation asserted type.  Otherwise, we
  659. ;;;    just use the node type.  If TYPE-CHECK is null, there is no point in
  660. ;;;    doing the intersection, since the node type must be a subtype of the
  661. ;;;    assertion.
  662. ;;;
  663. ;;; If the template is *not* ok, then the second value is a keyword indicating
  664. ;;; which aspect failed.
  665. ;;;
  666. (defun is-ok-template-use (template call safe-p)
  667.   (declare (type template template) (type combination call))
  668.   (let* ((guard (template-guard template))
  669.      (cont (node-cont call))
  670.      (atype (continuation-asserted-type cont))
  671.      (dtype (node-derived-type call)))
  672.     (cond ((and guard (not (funcall guard)))
  673.        (values nil :guard))
  674.       ((not (template-args-ok template call safe-p))
  675.        (values nil
  676.            (if (and safe-p (template-args-ok template call nil))
  677.                :arg-check
  678.                :arg-types)))
  679.       ((eq (template-result-types template) :conditional)
  680.        (let ((dest (continuation-dest cont)))
  681.          (if (and (if-p dest)
  682.               (immediately-used-p (if-test dest) call))
  683.          (values t nil)
  684.          (values nil :conditional))))
  685.       ((template-results-ok
  686.         template
  687.         (if (and (or (eq (template-policy template) :safe)
  688.              (not safe-p))
  689.              (continuation-type-check cont))
  690.         (values-type-intersection dtype atype)
  691.         dtype))
  692.        (values t nil))
  693.       (t
  694.        (values nil :result-types)))))
  695.  
  696.  
  697. ;;; Find-Template  --  Internal
  698. ;;;
  699. ;;;    Use operand type information to choose a template from the list
  700. ;;; Templates for a known Call.  We return three values:
  701. ;;; 1] The template we found.
  702. ;;; 2] Some template that we rejected due to unsatisfied type restrictions, or
  703. ;;;    NIL if none.
  704. ;;; 3] The tail of Templates for templates we haven't examined yet.
  705. ;;;
  706. ;;; We just call IS-OK-TEMPLATE-USE until it returns true.
  707. ;;;
  708. (defun find-template (templates call safe-p)
  709.   (declare (list templates) (type combination call))
  710.   (do ((templates templates (rest templates))
  711.        (rejected nil))
  712.       ((null templates)
  713.        (values nil rejected nil))
  714.     (let ((template (first templates)))
  715.       (when (is-ok-template-use template call safe-p)
  716.     (return (values template rejected (rest templates))))
  717.       (setq rejected template))))
  718.  
  719.  
  720. ;;; Find-Template-For-Policy  --  Internal
  721. ;;;
  722. ;;;    Given a partially annotated known call and a translation policy, return
  723. ;;; the appropriate template, or NIL if none can be found.  We scan the
  724. ;;; templates (ordered by increasing cost) looking for a template whose
  725. ;;; restrictions are satisfied and that has our policy.
  726. ;;;
  727. ;;; If we find a template that doesn't have our policy, but has a legal
  728. ;;; alternate policy, then we also record that to return as a last resort.  If
  729. ;;; our policy is safe, then only safe policies are O.K., otherwise anything
  730. ;;; goes.
  731. ;;;
  732. ;;; If we find a template with :SAFE policy, then we return it, or any cheaper
  733. ;;; fallback template.  The theory behind this is that if it is cheapest, small
  734. ;;; and safe, we can't lose.  If it is not cheapest, then we use the fallback,
  735. ;;; which won't have the desired policy, but :SAFE isn't desired either, so we
  736. ;;; might as well go with the cheaper one.  The main reason for doing this is
  737. ;;; to make sure that cheap safe templates are used when they apply and the
  738. ;;; current policy is something else.  This is useful because :SAFE has the
  739. ;;; additional semantics of implicit argument type checking, so we may be
  740. ;;; forced to define a template with :SAFE policy when it is really small and
  741. ;;; fast as well.
  742. ;;;
  743. (defun find-template-for-policy (call policy)
  744.   (declare (type combination call)
  745.        (type policies policy))
  746.   (let ((safe-p (policy-safe-p policy)))
  747.     (let ((current (function-info-templates (basic-combination-kind call)))
  748.       (fallback nil)
  749.       (rejected nil))
  750.       (loop
  751.     (multiple-value-bind (template this-reject more)
  752.                  (find-template current call safe-p)
  753.       (unless rejected
  754.         (setq rejected this-reject))
  755.       (setq current more)
  756.       (unless template
  757.         (return (values fallback rejected)))
  758.       
  759.       (let ((tpolicy (template-policy template)))
  760.         (cond ((eq tpolicy policy)
  761.            (return (values template rejected)))
  762.           ((eq tpolicy :safe)
  763.            (return (values (or fallback template) rejected)))
  764.           ((or (not safe-p) (eq tpolicy :fast-safe))
  765.            (unless fallback
  766.              (setq fallback template))))))))))
  767.  
  768.  
  769. (defvar *efficiency-note-limit* 2
  770.   "This is the maximum number of possible optimization alternatives will be
  771.   mentioned in a particular efficiency note.  NIL means no limit.")
  772. (proclaim '(type (or index null) *efficiency-note-limit*))
  773.  
  774. (defvar *efficiency-note-cost-threshold* 5
  775.   "This is the minumum cost difference between the chosen implementation and
  776.   the next alternative that justifies an efficiency note.")
  777. (proclaim '(type index *efficiency-note-cost-threshold*))
  778.  
  779.  
  780. ;;; STRANGE-TEMPLATE-FAILURE  --  Internal
  781. ;;;
  782. ;;;    This function is called by NOTE-REJECTED-TEMPLATES when it can't figure
  783. ;;; out any reason why Template was rejected.  Users should never see these
  784. ;;; messages, but they can happen in situations where the VM definition is
  785. ;;; messed up somehow.
  786. ;;;
  787. (defun strange-template-failure (template call policy frob)
  788.   (declare (type template template) (type combination call)
  789.        (type policies policy) (type function frob))
  790.   (funcall frob "This shouldn't happen!  Bug?")
  791.   (multiple-value-bind (win why)
  792.                (is-ok-template-use template call
  793.                        (policy-safe-p policy))
  794.     (assert (not win))
  795.     (ecase why
  796.       (:guard
  797.        (funcall frob "Template guard failed."))
  798.       (:arg-check
  799.        (funcall frob "Template is not safe, yet we were counting on it."))
  800.       (:arg-types
  801.        (funcall frob "Argument types invalid.")
  802.        (funcall frob "Argument primitive types:~%  ~S"
  803.         (mapcar #'(lambda (x)
  804.                 (primitive-type-name
  805.                  (ir2-continuation-primitive-type
  806.                   (continuation-info x))))
  807.             (combination-args call)))
  808.        (funcall frob "Argument type assertions:~%  ~S"
  809.         (mapcar #'(lambda (x)
  810.                 (if (atom x)
  811.                 x
  812.                 (ecase (car x)
  813.                   (:or `(:or .,(mapcar #'primitive-type-name
  814.                                (cdr x))))
  815.                   (:constant `(:constant ,(third x))))))
  816.             (template-arg-types template))))
  817.       (:conditional
  818.        (funcall frob "Conditional in a non-conditional context."))
  819.       (:result-types
  820.        (funcall frob "Result types invalid.")))))
  821.  
  822.  
  823. ;;; Note-Rejected-Templates  --  Internal
  824. ;;;
  825. ;;;    This function emits efficiency notes describing all of the templates
  826. ;;; better (faster) than Template that we might have been able to use if there
  827. ;;; were better type declarations.  Template is null when we didn't find any
  828. ;;; template, and thus must do a full call.
  829. ;;;
  830. ;;; In order to be worth complaining about, a template must:
  831. ;;; -- be allowed by its guard,
  832. ;;; -- be safe if the current policy is safe,
  833. ;;; -- have argument/result type restrictions consistent with the known type
  834. ;;;    information, e.g. we don't consider float templates when an operand is
  835. ;;;    known to be an integer,
  836. ;;; -- be disallowed by the stricter operand subtype test (which resembles, but
  837. ;;;    is not identical to the test done by Find-Template.)
  838. ;;;
  839. ;;; Note that there may not be any possibly applicable templates, since we are
  840. ;;; called whenever any template is rejected.  That template might have the
  841. ;;; wrong policy or be inconsistent with the known type.
  842. ;;;
  843. ;;; We go to some trouble to make the whole multi-line output into a single
  844. ;;; call to Compiler-Note so that repeat messages are suppressed, etc.
  845. ;;;
  846. (defun note-rejected-templates (call policy template)
  847.   (declare (type combination call) (type policies policy)
  848.        (type (or template null) template))
  849.  
  850.   (collect ((losers))
  851.     (let ((safe-p (policy-safe-p policy))
  852.       (verbose-p (policy call (= brevity 0)))
  853.       (max-cost (- (template-cost
  854.             (or template
  855.                 (template-or-lose 'call-named *backend*)))
  856.                *efficiency-note-cost-threshold*)))
  857.       (dolist (try (function-info-templates (basic-combination-kind call)))
  858.     (when (> (template-cost try) max-cost) (return))
  859.     (let ((guard (template-guard try)))
  860.       (when (and (or (not guard) (funcall guard))
  861.              (or (not safe-p)
  862.              (policy-safe-p (template-policy try)))
  863.              (or verbose-p
  864.              (and (template-note try)
  865.                   (valid-function-use
  866.                    call (template-type try)
  867.                    :argument-test #'types-intersect
  868.                    :result-test #'values-types-intersect))))
  869.         (losers try)))))
  870.  
  871.     (when (losers)
  872.       (collect ((messages)
  873.         (count 0 +))
  874.     (flet ((frob (string &rest stuff)
  875.          (messages string)
  876.          (messages stuff)))
  877.       (dolist (loser (losers))
  878.         (when (and *efficiency-note-limit*
  879.                (>= (count) *efficiency-note-limit*))
  880.           (frob "etc.")
  881.           (return))
  882.         (let* ((type (template-type loser))
  883.            (valid (valid-function-use call type))
  884.            (strict-valid (valid-function-use call type
  885.                              :strict-result t)))
  886.           (frob "Unable to do ~A (cost ~D) because:"
  887.             (or (template-note loser) (template-name loser))
  888.             (template-cost loser))
  889.           (cond
  890.            ((and valid strict-valid)
  891.         (strange-template-failure loser call policy #'frob))
  892.            ((not valid)
  893.         (assert (not (valid-function-use call type
  894.                          :error-function #'frob
  895.                          :warning-function #'frob))))
  896.            (t
  897.         (assert (policy-safe-p policy))
  898.         (frob "Can't trust output type assertion under safe ~
  899.                policy.")))
  900.           (count 1))))
  901.  
  902.     (let ((*compiler-error-context* call))
  903.       (compiler-note "~{~?~^~&~6T~}"
  904.              (if template
  905.                  `("Forced to do ~A (cost ~D)."
  906.                    (,(or (template-note template)
  907.                      (template-name template))
  908.                 ,(template-cost template))
  909.                    . ,(messages))
  910.                  `("Forced to do full call."
  911.                    nil
  912.                    . ,(messages))))))))
  913.   (undefined-value))
  914.  
  915.  
  916.  
  917. ;;; Flush-Type-Checks-According-To-Policy  --  Internal
  918. ;;;
  919. ;;;    Flush type checks according to policy.  If the policy is unsafe, then we
  920. ;;; never do any checks.  If our policy is safe, and we are using a safe
  921. ;;; template, then we can also flush arg and result type checks.  Result type
  922. ;;; checks are only flushed when the continuation as a single use.
  923. ;;;
  924. (defun flush-type-checks-according-to-policy (call policy template)
  925.   (declare (type combination call) (type policies policy)
  926.        (type template template))
  927.   (let ((safe-op (eq (template-policy template) :safe)))
  928.     (when (or (not (policy-safe-p policy)) safe-op)
  929.       (dolist (arg (basic-combination-args call))
  930.     (flush-type-check arg)))
  931.     (when safe-op
  932.       (let ((cont (node-cont call)))
  933.     (when (eq (continuation-use cont) call)
  934.       (flush-type-check cont)))))
  935.  
  936.   (undefined-value))
  937.  
  938.  
  939. ;;; LTN-Analyze-Known-Call  --  Internal
  940. ;;;
  941. ;;;    If a function has a special-case annotation method use that, otherwise
  942. ;;; annotate the argument continuations and try to find a template
  943. ;;; corresponding to the type signature. If there is none, convert a full
  944. ;;; call.
  945. ;;;
  946. ;;;    If we are unable to use some templates due to unstatisfied operand type
  947. ;;; restrictions and our policy enables efficiency notes, then we call
  948. ;;; Note-Rejected-Templates.
  949. ;;;
  950. ;;;    If we are forced to do a full call, we check to see if the function
  951. ;;; called is the same as the current function.  If so, we give a warning, as
  952. ;;; this is probably a botched interpreter stub.
  953. ;;;
  954. (defun ltn-analyze-known-call (call policy)
  955.   (declare (type combination call)
  956.        (type policies policy))
  957.   (let ((method (function-info-ltn-annotate (basic-combination-kind call)))
  958.     (args (basic-combination-args call)))
  959.     (when method
  960.       (funcall method call policy)
  961.       (return-from ltn-analyze-known-call (undefined-value)))
  962.     
  963.     (dolist (arg args)
  964.       (setf (continuation-info arg)
  965.         (make-ir2-continuation (primitive-type (continuation-type arg)))))
  966.  
  967.     (multiple-value-bind (template rejected)
  968.              (find-template-for-policy call policy)
  969.       (when (and rejected
  970.          (policy call (> speed brevity)))
  971.     (note-rejected-templates call policy template))
  972.       (unless template
  973.     (when (and (eq (continuation-function-name (combination-fun call))
  974.                (leaf-name
  975.             (environment-function
  976.              (node-environment call))))
  977.            (let ((info (basic-combination-kind call)))
  978.              (not (or (function-info-ir2-convert info)
  979.                   (ir1-attributep (function-info-attributes info)
  980.                           recursive)))))
  981.       (let ((*compiler-error-context* call))
  982.         (compiler-warning "Recursive known function definition.")))
  983.     (ltn-default-call call policy)
  984.     (return-from ltn-analyze-known-call (undefined-value)))
  985.       (setf (basic-combination-info call) template)
  986.       (setf (node-tail-p call) nil)
  987.       
  988.       (flush-type-checks-according-to-policy call policy template)
  989.       
  990.       (dolist (arg args)
  991.     (annotate-1-value-continuation arg))))
  992.   
  993.   (undefined-value))
  994.  
  995.  
  996. ;;;; Interfaces:
  997.  
  998. (eval-when (compile eval)
  999.  
  1000. ;;; LTN-Analyze-Block-Macro  --  Internal
  1001. ;;;
  1002. ;;;    We make the main per-block code in for LTN into a macro so that it can
  1003. ;;; be shared between LTN-Analyze and LTN-Analyze-Block, yet can cache policy
  1004. ;;; across blocks in the normal (full component) case.
  1005. ;;;
  1006. ;;;    This code computes the policy and then dispatches to the appropriate
  1007. ;;; node-specific function.
  1008. ;;;
  1009. ;;; Note: we deliberately don't use the DO-NODES macro, since the block can be
  1010. ;;; split out from underneath us, and DO-NODES scans past the block end in this
  1011. ;;; case.
  1012. ;;;
  1013. (defmacro ltn-analyze-block-macro ()
  1014.   '(do* ((node (continuation-next (block-start block))
  1015.            (continuation-next cont))
  1016.      (cont (node-cont node) (node-cont node)))
  1017.     (())
  1018.      (unless (eq (node-lexenv node) lexenv)
  1019.        (setq policy (translation-policy node))
  1020.        (setq lexenv (node-lexenv node)))
  1021.          
  1022.      (etypecase node
  1023.        (ref)
  1024.        (combination
  1025.     (case (basic-combination-kind node)
  1026.       (:local (ltn-analyze-local-call node policy))
  1027.       (:full (ltn-default-call node policy))
  1028.       (t
  1029.        (ltn-analyze-known-call node policy))))
  1030.        (cif
  1031.     (ltn-analyze-if node policy))
  1032.        (creturn
  1033.     (ltn-analyze-return node policy))
  1034.        ((or bind entry))
  1035.        (exit
  1036.     (ltn-analyze-exit node policy))
  1037.        (cset (ltn-analyze-set node policy))
  1038.        (mv-combination
  1039.     (ecase (basic-combination-kind node)
  1040.       (:local (ltn-analyze-mv-bind node policy))
  1041.       (:full (ltn-analyze-mv-call node policy)))))
  1042.  
  1043.      (when (eq node (block-last block)) (return))))
  1044.  
  1045. ); Eval-When (Compile Eval)
  1046.  
  1047.  
  1048. ;;; LTN-Analyze  --  Interface
  1049. ;;;
  1050. ;;;    Loop over the blocks in Component, doing stuff to nodes that receive
  1051. ;;; values.  In addition to the stuff done by LTN-Analyze-Block-Macro, we also
  1052. ;;; see if there are any unknown values receivers, making notations in the
  1053. ;;; components Generators and Receivers as appropriate.
  1054. ;;;
  1055. ;;;    If any unknown-values continations are received by this block (as
  1056. ;;; indicated by IR2-Block-Popped, then we add the block to the
  1057. ;;; IR2-Component-Values-Receivers.
  1058. ;;;
  1059. ;;;    This is where we allocate IR2 blocks because it is the first place we
  1060. ;;; need them.
  1061. ;;;
  1062. (defun ltn-analyze (component)
  1063.   (declare (type component component))
  1064.   (let ((2comp (component-info component))
  1065.     (lexenv nil)
  1066.     policy)
  1067.     (do-blocks (block component)
  1068.       (assert (not (block-info block)))
  1069.       (let ((2block (make-ir2-block block)))
  1070.     (setf (block-info block) 2block)
  1071.     (ltn-analyze-block-macro)
  1072.     (let ((popped (ir2-block-popped 2block)))
  1073.       (when popped
  1074.         (push block (ir2-component-values-receivers 2comp)))))))
  1075.   (undefined-value))
  1076.  
  1077.  
  1078. ;;; LTN-Analyze-Block  --  Interface
  1079. ;;;
  1080. ;;;    This function is used to analyze blocks that must be added to the flow
  1081. ;;; graph after the normal LTN phase runs.  Such code is constrained not to
  1082. ;;; use weird unknown values (and probably in lots of other ways).
  1083. ;;;
  1084. (defun ltn-analyze-block (block)
  1085.   (declare (type cblock block))
  1086.   (let ((lexenv nil)
  1087.     policy)
  1088.     (ltn-analyze-block-macro))
  1089.  
  1090.   (assert (not (ir2-block-popped (block-info block))))
  1091.   (undefined-value))
  1092.